package apoc.core.network.packet;

import apoc.core.entity.ApocPlayerProperties;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;

import java.io.IOException;

public class SyncPlayerPacket implements IApocPacket
{

    private String name;
    private NBTTagCompound data;

    public SyncPlayerPacket()
    {

    }

    public SyncPlayerPacket(EntityPlayer player)
    {
        this.name = player.getCommandSenderName();
        this.data = new NBTTagCompound();
        ApocPlayerProperties.getByEntity(player).saveNBTData(data);
    }

    @Override
    public void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer)
    {
        try
        {
            buffer.writeInt(name.getBytes().length);
            buffer.writeBytes(name.getBytes());
            byte[] byteData = CompressedStreamTools.compress(data);
            buffer.writeInt(byteData.length);
            buffer.writeBytes(byteData);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer)
    {
        try
        {
            int length = buffer.readInt();
            name = new String(buffer.readBytes(length).array());
            data = CompressedStreamTools.decompress(buffer.readBytes(buffer.readInt()).array());
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void handleClientSide(EntityPlayer player)
    {
        if (player.getCommandSenderName().equals(name))
        {
            ApocPlayerProperties.getByEntity(player).loadNBTData(data);
        } else
        {
            ApocPlayerProperties.getByEntity(player.worldObj.getPlayerEntityByName(name)).loadNBTData(data);
        }
    }

    @Override
    public void handleServerSide(EntityPlayer player)
    {

    }
}
